package com.heima.comment.service.impl;
/*
    
 需求描述：
 @Author: wang
 @Date: 2022/10/22 17:12
 
 */

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.comment.mongo.ApComment;
import com.heima.comment.mongo.ApCommentLike;
import com.heima.comment.service.ApArticleService;
import com.heima.comment.service.ApAuthorService;
import com.heima.comment.service.CommentService;
import com.heima.comment.utils.WmThreadLocalUtil;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private ApAuthorService authorService;

    @Autowired
    private ApArticleService articleService;

    /**
     * 评论保存
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult saveComment(CommentSaveDto dto) throws Exception {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //必须登录后才能发表评论
        //todo 写死用户已登录 userId为  4，待网关完成后再完善
        //String userId = request.getHeader("userId");

        WmUser user = WmThreadLocalUtil.getUser();

        dto.setUserId(user.getId());
//        Integer userId = dto.getUserId();
        if (StringUtils.isBlank(String.valueOf(user.getId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //dto.setUserId(Integer.parseInt(userId));
        //评论内容不能超过140字
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //评论内容需要做文本垃圾检测
        String suggestion = greenTextScan.greeTextScan(dto.getContent()).get("suggestion").toString();
        if (StringUtils.isNotBlank(suggestion) && !"pass".equals(suggestion)) {
            return ResponseResult.errorResult(501, "评论内容违规");
        }
        // 保存评论数据到mongoDB
        saveCommentToMongo(dto);
        //给文章的评论量加一
        ApArticle article = articleService.getById(dto.getArticleId());
        article.setComment(article.getComment()+1);
        articleService.updateById(article);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadComment(CommentDto dto) {
        Query query = Query.query(Criteria.where("createdTime").lt(dto.getMinDate()).andOperator(Criteria.where("articleId").is(dto.getArticleId())))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(dto.getIndex() * 10);
        List<ApComment> apAssociateWordsList = mongoTemplate.find(query, ApComment.class);
        // 封装结果

        List<Map<String, Object>> list = packageResultData(apAssociateWordsList);

        return ResponseResult.okResult(list);
    }

    /**
     * 点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeComment(CommentLikeDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }


//
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).andOperator(Criteria.where("userId").is(WmThreadLocalUtil.getUser().getId())));
        ApCommentLike commentLike = mongoTemplate.findOne(query, ApCommentLike.class);
        //第一次点赞创建点赞数据
        if (commentLike==null){
            commentLike = new ApCommentLike();
        }
        commentLike.setCommentId(dto.getCommentId());
        commentLike.setOperation(dto.getOperation());
        commentLike.setCreatedTime(new Date());
        commentLike.setUserId(WmThreadLocalUtil.getUser().getId());
        mongoTemplate.save(commentLike);

        //给评论总点赞数量做修改

        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (dto.getOperation() == 1) {
            apComment.setLikes(apComment.getLikes() - 1);
        }
        if (dto.getOperation() == 0) {
            apComment.setLikes(apComment.getLikes() + 1);
        }
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 封装结果
     *
     * @param apAssociateWordsList
     * @return
     */
    private List<Map<String, Object>> packageResultData(List<ApComment> apAssociateWordsList) {

        List<Map<String, Object>> list = new ArrayList();
        for (ApComment apComment : apAssociateWordsList) {
            if (apAssociateWordsList.size() > 0 && apComment != null) {
                list.add(builderComment(apComment));
            }
        }
        return list;
    }

    /**
     * 给comment设置值
     *
     * @param apComment
     * @return
     */


    private Map builderComment(ApComment apComment) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", apComment.getId());
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getUserId, apComment.getUserId()));

        map.put("authorId", apAuthor.getId());
        map.put("authorName", apAuthor.getName());
        map.put("entryId", apComment.getArticleId());
        map.put("channelId", null);
        map.put("type", 0);
        map.put("content", apComment.getContent());
        map.put("image", null);
        map.put("likes", apComment.getLikes());
        map.put("reply", apComment.getReplies());
        map.put("flag", 0);
        map.put("longitude", null);
        map.put("latitude", null);
        map.put("address", null);
        map.put("ord", null);
        map.put("createdTime", apComment.getCreatedTime());
        map.put("updatedTime", null);
        map.put("operation", null);

        return map;
    }

    /**
     * 保存数据到mongo
     *
     * @param dto
     */
    private void saveCommentToMongo(CommentSaveDto dto) {
        ApComment apComment = new ApComment();
        BeanUtils.copyProperties(dto, apComment);
        apComment.setCreatedTime(new Date());
        apComment.setLikes(0);
        apComment.setReplies(0);
        mongoTemplate.save(apComment);
    }
}
